package com.ylink.epcc;

import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.common.collect.Maps;
import com.ylink.epcc.common.enums.DrctnCdEnum;
import com.ylink.epcc.common.utils.CommonUtil;
import com.ylink.epcc.common.utils.Obj2XmlUtil;
import com.ylink.sky.util.tools.DateUtil;

@Slf4j
public class MockUtil {
	private static final String FTL = "com/ylink/epcc/mock209.ftl";

	public static String httpPostXml(String url, String xml) {
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			try {
				HttpPost httppost = new HttpPost(url);
				StringEntity myEntity = new StringEntity(xml);
				httppost.setHeader("Content-Type", "application/xml; charset=utf-8");
				httppost.setEntity(myEntity);
				CloseableHttpResponse response = httpclient.execute(httppost);
				try {
					HttpEntity resEntity = response.getEntity();
					String res = EntityUtils.toString(resEntity);
					EntityUtils.consume(resEntity);
					return res;
				} finally {
					response.close();
				}
			} finally {
				httpclient.close();
			}

		} catch (Exception e) {
//			log.error("http post提交XML报错", e);
		}
		return "";
	}

	public static String getTrxid() {
		return DateUtil.getNowDate("yyyyMMddHHmmssSSS") + RandomStringUtils.randomNumeric(14);
	}

	public static String genM209Xml() {
		ThreadLocalRandom tlr = ThreadLocalRandom.current();
		int i = tlr.nextInt(5);
		String[] s = { "11111111111111", "22222222222222", "11111111111111", "22222222222222", "33333333333333" };
		Map<String, Object> map = Maps.newHashMap();
		map.put("sndDt", CommonUtil.getNowTm());
		map.put("msgTp", "epcc.209.001.01");
		map.put("issrId", CommonUtil.getIssrId());
		map.put("drcTn", DrctnCdEnum.CD_22.getEnValue());
		map.put("signSN", CommonUtil.getSignSN());
		map.put("ncrptnSN", "");
		map.put("dgtlEnvlp", "");

		map.put("trxId", getTrxid());// 交易流水号
		map.put("instgId", s[i]);// 支付机构标识号
		map.put("sgnNo", "");// 协议号
		String xml = Obj2XmlUtil.process(FTL, map);
//		log.info("gen 209 xml :{}", xml);
		return xml;
	}

}
